﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using KJFrame.Core.Rpc.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;

namespace KJFrame.Core.ClientApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        /// <summary>
        /// 服务
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            //services
            //    .AddRpcClient(Configuration)
            //    .AddRpcClientService<IUserService>()
            //    .BuildServiceProvider();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "client demo", Version = "v1" });
                var xmls = GetXmls();
                if (xmls != null)
                {
                    foreach (var item in xmls)
                    {
                        c.IncludeXmlComments(item);
                    }
                }
            });
            services.AddRpcClient(Configuration).AddRpcClientService().BuildServiceProvider();
        }

        /// <summary>
        /// 管道
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "client api");
            });
            app.UseMvc();
        }

        /// <summary>
        /// 获取 SwaggerUI的Document文档注释
        /// </summary>
        /// <returns></returns>
        private string[] GetXmls()
        {
            var basePath = PlatformServices.Default.Application.ApplicationBasePath;
            var fileList = Directory.GetFiles(basePath, "*.xml");
            return fileList;
        }
    }

}
